<template>
  <div>
    <el-button
      size="small"
      icon="el-icon-printer"
      class="print-btn"
      @click="$print($refs.print, null)"
    >
      打印
    </el-button>
    <div class="officeBuy" ref="print">
      <el-popover
        placement="bottom-end"
        width="600"
        trigger="hover"
        content="办公用品类别：
        A类（办公设备、家具等计入固定资产的办公用品）：1.设备类：服务器（仅限于非系统集成项目）、台式计算机、便携式计算机、路由器、交换设备、网络控制设备、网络检测设备、防火墙、打印设备、显示器（指台式电脑的液晶显示器）、扫描仪、计算机软件（指可以直接从市场购买的标准换件等非定制开发的商用软件）、复印机、投影仪及幕布、多功能一体机、照相机及器材、LED显示屏、刻录机、速印机、装订机、碎纸机、电视机、传真机、摄像机、电话机、电风扇、饮水机、取暖器等；2.家具类：桌、椅、凳、柜、箱、沙发、茶几等。
        B类（办公设备配件、耗材等不计入固定资产的办公用品）：1.配件类：存储设备（内存、硬盘、U盘、光盘）、电脑配件和外设、电源设备、设备电池等；2.耗材类：硒鼓、墨盒、墨粉、色带、色带架等。
        C类（不计入固定资产的低值办公用品）：纸张（打（复）印纸、封面纸、笔记本、信签等）、书写工具（笔、墨、印泥、橡皮擦、修正液、便签条等）、财务用品（计算器、尺子、标签等）、会议用品（茶叶、水杯、水壶、瓶装水、纸巾等）、收纳用品（档案袋、文件夹、凭证盒、信封等）、装订用品（订书机、订书针、图钉、回形针、夹子、剪刀、胶水等）、簿本册、劳保用品、劳动工具等。
        D类：其他未列入A、B、C类办公用品的办公易耗品。"
      >
        <div class="title" slot="reference">
          中共文山州委办公室办公用品采购申请单
        </div>
      </el-popover>
      <div class="company">
        <span>
          局、馆、科、中心：{{  pager.department || department_name }}
        </span>
        <span>
          {{ parseTime(pager.create_time || new Date(), "{y}年{m}月{d}日") }}
        </span>
      </div>
      <div>
        <table class="table-wrapper" border="1px" cellspacing="0" cellpadding="0">
          <tr height="60">
            <td width="6%" align="center">类别</td>
            <td width="12%" align="center">办公室用品</td>
            <td width="6%" align="center">新增/更换</td>
            <td width="10%" align="center">数量</td>
            <td width="10%" align="center">单价（元）</td>
            <td width="8%" align="center">金额（元）</td>
            <td width="10%" align="center">使用人</td>
          </tr>
          <tr 
            height="40" 
            v-for="(row, index) in dataSource" 
            :key="index"
            @mousemove="moveIndex = index"
            @mouseleave="moveIndex = null"
          >
            <td style="position: relative" align="center">
              <div :class="!hasData && moveIndex === index ? 'toolbar' : 'hidden'">
                <i class="el-icon-minus icon" @click="handDeleteRecord(index)"></i>
                <i class="el-icon-plus icon" @click="handAddRecord(index)"></i>
              </div>
              <span class="content" v-if="hasData">{{ row.type }}</span>
              <el-select v-else v-model="row.type">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </td>
            <td align="center">
              <span class="content" v-if="hasData">{{ row.bgyp }}</span>
              <el-input v-else v-model="row.bgyp" placeholder="请输入" />
            </td>
            <td align="center">
              <span class="content" v-if="hasData">{{ row.xz_gh }}</span>
              <el-select v-else v-model="row.xz_gh">
                <el-option
                  v-for="item in replaceOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </td>
            <td align="center">
              <span class="content" v-if="hasData">{{ row.nums }}</span>
              <el-input-number 
                v-else
                v-model="row.nums" 
                controls-position="right" 
                :min="1" 
                label="请输入"
                style="width: 100%"
                @change="value => handleChangeNumber(index, row, value)"
              />
            </td>
            <td align="center">
              <span class="content" v-if="hasData">{{ row.unit_price }}</span>
              <el-input-number
                v-else 
                v-model="row.unit_price" 
                controls-position="right" 
                :precision="1"
                :min="0.1" 
                label="请输入"
                style="width: 100%"
                @change="value => handleChangeNumber(index, row, value)"
              />
            </td>
            <td align="center">
              <span class="content">{{ row.total_price }}</span>
            </td>
            <td align="center">
              <span class="content" v-if="hasData">{{ row.user }}</span>
              <el-input v-else v-model="row.user" placeholder="请输入" />
            </td>
          </tr>
          <tr height="40">
            <td colspan="3" align="center">合计</td>
            <td align="center">{{summary.counts}}</td>
            <td align="center"></td>
            <td align="center">{{summary.amounts}}</td>
            <td align="center"></td>
          </tr>
          </table>
          <table class="table-wrapper bottomTable" border="1px" cellspacing="0" cellpadding="0">
            <tr height="120">
              <td align="center" class="advice">
                <span class="name">后勤分管领导：</span>
                <div v-html="getLeaderAdvice('后勤分管领导')"></div>
              </td>
              <td align="center" class="advice">
                <span class="name">科室分管领导：</span>
                <div v-html="getLeaderAdvice('科室分管领导')"></div>
              </td>
              <td align="center" class="advice">
                <span class="name">行政财务科：</span>
                <div v-html="getLeaderAdvice('行政财务科')"></div>
              </td>
              <td align="center" class="advice">
                <span class="name">科室负责人：</span>
                <div v-html="getLeaderAdvice('科室负责人')"></div>
              </td>
            </tr>
            <tr v-if="showAdviceInput && !queryData.isHand" class="situation">
              <td align="center">审批意见</td>
              <td colspan="3">
                <el-input
                  type="textarea"
                  :rows="2"
                  v-model="comment"
                  placeholder="填写意见"
                ></el-input>
              </td>
            </tr>
          </table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { parseTime } from "@/utils/index.js";
export default {
  name: "OfficeBuy",
   computed: {
    ...mapGetters(["id", "first_name", "department_name"]),
  },
  props: {
    pager: {
      type: Object,
      default: () => ({}),
    },
    queryData: {
      type: Object,
      default: () => ({}),
    },
    pointData: {
      type: Object,
      default: () => ({}),
    },
    showAdviceInput: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      hasData: false,
      dataSource: [],
      comment: '',
      moveIndex: null,
      intiRecord: {
        type: 'A类',
        bgyp: '',
        xz_gh: '新增',
        nums: null,
        unit_price: 100,
        total_price: 100,
        user: ''
      },
      summary: {
        counts: 0,
        amounts: 0
      },
      typeOptions: [
        {id: 1, name: 'A类'},
        {id: 2, name: 'B类'},
        {id: 3, name: 'C类'},
        {id: 4, name: 'D类'}
      ],
      replaceOptions: [
        {id: 1, name: '新增'},
        {id: 2, name: '更换'}
      ],
    };
  },
  watch: {
    pager: {
      handler(data) {
        if (data && data.apply_detail) {
          this.dataSource = data.apply_detail
          this.hasData = true;
        }
      },
      immediate: true,
    },
    dataSource: {
      handler(data) {
        let counts = 0
        let amounts = 0
        data.forEach(record => {
          const { nums, total_price } = record
          counts += nums
          amounts += (+total_price)
        });
        this.summary = {
          counts,
          amounts: amounts.toFixed(1)
        }
      },
      immediate: true,
      deep: true
    },
  },
  mounted() {
    if(!this.dataSource.length) {
      this.initDataSource()
    }
  },
  methods: {
    parseTime,
    // 初始化申请单数组
    initDataSource(count = 4) {
      this.dataSource = new Array(count).fill(null).map(() => ({...this.intiRecord}))
    },
    // 根据审批节点名称 获得对应建议
    getLeaderAdvice(leader) {
      const point = this.pointData[leader] || [];
      let adviceStr = ''
      if (point.length) {
        point.forEach(item => {
          const { message, userId, time } = item;
          const first_name = userId && userId.split("(")[0];
          adviceStr += `${message}（${first_name} ${parseTime(time, "{y}-{m}-{d} {h}:{i}")}）<br>`
        })
      }
      return adviceStr;
    },
    // 点击加号 新增记录
    handAddRecord(index) {
      this.dataSource.splice(index, 0, {...this.intiRecord})
    },
    // 点击减号 移出记录
    handDeleteRecord(index) {
      if(this.dataSource.length === 1) return
      this.dataSource.splice(index, 1);
    },
    // 数量和价格变动时动态计算总价
    handleChangeNumber(index, row, value) {
      const { nums, unit_price } = row
      row.total_price = (nums * unit_price).toFixed(1)
    }
  },
};
</script>
<style lang="scss">
.print-btn {
  position: absolute;
  right: 20px;
}
.officeBuy {
  .title {
    width: 100%;
    text-align: center;
    font-size: 30px;
    padding-top: 40px;
    margin: 0px auto 52px;
    max-width: 900px;
    cursor: pointer;
  }
  .company {
    margin: 0 auto;
    max-width: 900px;
    margin-top: 34px;
    padding: 0 13px 4px 13px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    span {
      line-height: 14px;
    }
  }
  .table-wrapper {
    width: 100%;
    margin: 0 auto !important;
    max-width: 900px;
    font-size: 14px;
    border-collapse: collapse;

    .toolbar {
      content: '';
      width: 20px;
      height: 100%;
      padding: 2px 0;
      position: absolute;
      top: 0;
      left: -21px;
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      align-content: center;
      justify-content: space-between;
      align-items: center;
      .icon {
        cursor: pointer;
      }
    }
    .hidden {
      display: none;
    }
    .advice {
      width: 25%;
      position: relative;
      padding-left: 17px;
      padding-top: 36px;
      text-align: left;
      vertical-align: top;
      .name {
        position: absolute;
        top: 14px;
        left: 16px;
        z-index: 99;
        line-height: 14px;
      }
      > div {
        line-height: 24px;
      }
    }
  }
}
</style>